package com.kmxd.ams.init;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SmUtil;
import com.kmxd.ams.client.system.ISysUserSvc;
import com.kmxd.ams.infra.system.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 系统启动后自动执行升级内容
 *
 * @author zuolg
 */
@Component
@Slf4j
public class InitUpgradeV5 {
    @Value("${defPassword}")
    private String defPassword;

    @Autowired
    private ISysUserSvc sysUserSvc;
    private static final String PWD_DEF_SALT = "d3d3LmtteGRrai5jbg==";
    private static final String INFO_FORMAT_TEMP = "{}:{}";


    /**
     * v4 升级业务行为
     */
    public void resetPassword() {
        System.out.println("---- 用户密码重置：开始");
        if (CharSequenceUtil.isBlank(defPassword)) {
            System.out.println("---- 用户密码重置：请设置默认密码，参数名：defPassword");
            return;
        }

        List<SysUser> list = sysUserSvc.list();
        if (ObjectUtil.isEmpty(list)) {
            System.out.println("---- 用户密码重置：用户为空，不修改密码");
            return;
        }
        list.forEach(user -> {
            String encryptPassword = encryptPassword(defPassword, String.valueOf(user.getId()), user.getAccount());
            user.setPassword(encryptPassword);
        });

        sysUserSvc.updateBatchById(list);
        System.out.println("---- 用户密码重置：重置用户密码成功");
    }

    public static String format(Object... params) {
        String format = CharSequenceUtil.format(INFO_FORMAT_TEMP, PWD_DEF_SALT, params);
        return Base64.encode(format);
    }

    public static String encryptPassword(String password, String salt, String salt1) {
        String info = format(salt, salt1, password);
        return SmUtil.sm3(info);
    }
}
